#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2021/8/2 11:27
@File: queryJira.py
"""
import json
import re

import requests

from job.src.function.record_log import mylog
from job.src.function.SeleniumOperation import GetSessionAndToken
from job.src.function.http_opration import requestPost


def get_jsession(**params):
    cookies = ''
    obj = GetSessionAndToken(params.get('isClose', True))
    obj.login_system(**params)
    cookies_list = obj.get_cookie()
    if params.get('getToken'):
        tooken = obj.get_token('se.SEConfig.token')
        tookenstr = f'token={tooken};'
        cookies += tookenstr
    obj.close()
    for dic in cookies_list:
        name = dic['name']
        value = dic['value']
        t_info = f'{name}={value}; '
        cookies += t_info
    cookies = cookies.rstrip('; ')
    mylog.info(f'cookies: {cookies}')
    return cookies

def query_issue(jsql, cookies):
    '''
    查询我报告的问题
    :param jsql: 筛选条件，拷贝切换高级后的语句即可
    :param cookies: 登录jira后获取的cookies
    :return:
    '''
    url = 'https://se.hundsun.com/rest/issueNav/1/issueTable'
    header ={
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': cookies,
        '__amdModuleName': 'jira/issue/utils/xsrf-token-header',
        'X-Atlassian-Token': 'no-check',
        'X-Requested-With': 'XMLHttpRequest'
    }
    data = {
        'startIndex': '0',
        'filterId': '-2',
        'jql': jsql,
        'layoutKey': 'list-view'
    }
    res = requests.post(url, data=data, headers=header)
    status = res.status_code
    if status == 200:
        res_info = res.json()
        res_list = res_info['issueTable']['issueKeys']
    else:
        res_list = []
    return res_list

def query_modify(updateData=None, param=None, cookies=None, token=None):
    url = 'https://ts.hundsun.com/se/services/modify/fetchModifyByUserdefinedModluePaginatedLucene.htm'
    headers = {
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': cookies,
        'Referer': 'https://ts.hundsun.com/se/services/modify/fetchModifyByUserdefinedModluePaginatedLucene.htm',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
    }
    data = {
        'param': json.dumps(param),
        'token': token,
    }
    data.update(updateData)
    mylog.info(data)
    res = requestPost(url, data=data, headers=headers)
    mylog.info(f'result:{res}')
    # mylog.info(f'text: {res.text}')
    if res.status_code == 200:
        return json.loads(res.text)
    else:
        return {}

def queryModiyMainProcess(loginfo, data, params):
    jsesion = get_jsession(**loginfo)
    token = re.search(r'token=(.*?);', jsesion)
    mylog.info(f'token: {token[1]}')
    response = query_modify(data, params, cookies=jsesion, token=token[1])
    resList = response.get("resultBOList")
    # mylog.info(f'resList: {resList}')
    return resList

def data_parse(resList, type=1):
    '''
    解析提取关键信息返回
    :param resList:
    :param type:
    :return:
    '''
    newDict = {}
    if type == 0 and resList:
        '''
        返回数据格式：{tester: 'md01,md02,', other: 'md01,md02,'}
        '''
        for unit in resList:
            mylog.info(f"productId: {unit.get('productId')}; modifyNum: {unit.get('modifyNum')}; tester: {unit.get('tester')}")
            name = unit.get('tester')
            nums = unit.get('modifyNum')
            if name:
                newDict[name] = newDict.get(name, "") + nums + ','
            else:
                newDict['other'] = newDict.get('other', "") + nums + ','
        mylog.info(f'newDict: {newDict}')
    elif type == 1 and resList:
        '''
        返回数据格式：{version: [tester01,tester02]}
        '''
        for unit in resList:
            mylog.info(f"productId: {unit.get('productId')}; modifyNum: {unit.get('modifyNum')};"
                     f"tester: {unit.get('tester')}; testPackageName: {unit.get('testPackageName')}")
            name = unit.get('tester', '')
            version = unit.get('testPackageName')
            newDict[version] = newDict.get(version, "") + name + ','
        for key, value in newDict.items():
            newValue = list(set(value.rstrip(',').split(',')))
            newDict[key] = newValue
        mylog.info(f'newDict: {newDict}')
    else:
        mylog.error(f'参数错误，请检查：resList：{resList}, type: {type}')
    return newDict



if __name__ == '__main__':
    loginfo = {'username': 'lijk34925', 'password': 'eGluZ0AyMDIx', 'getToken': True, 'isClose': True,
               'jira_url': 'https://hs-cas.hundsun.com/cas/login?service=https%3A%2F%2Fts.hundsun.com%2Fse%2Fj_spring_cas_security_check',
               }
    params = {
        "productId": "20160406",
        "modifyStatus": "5,6"
    }
    # queryModiyMainProcess(loginfo, params)
    pass